package com.example.springboot01.filter;

import com.example.springboot01.entity.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;

public class MVCInterceptor implements HandlerInterceptor {

    @Override
    //本程序不能处理Android和h5小程序过来的请求，
    // 因为此类访问都是ajax类型，没有session,但是可以通过token来解决这个问题。一样能处理
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler){
        boolean flag = true;
        //打印出调用请求的URL地址
        String requestURL = request.getRequestURI();
        System.out.println(requestURL);
        UserInfo userInfo = (UserInfo) request.getSession().getAttribute("user_info");
//        System.out.println("filer:" + userInfo.toString() + "查看数据是否出错");
        if (userInfo == null){//session不存在则跳转到重新登录
            flag = false;
            try {
                response.sendRedirect("show_login");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //以下添加权限检测代码，如果不能执行此操作，可以建议过滤掉。
//        String[] request_url = requestURL.split(";");
//        String request_name = request_url[0];
//        //System.out.println(request_name);
//        Privilege_InfoService privilege_infoService =
//                (Privilege_InfoService) SpringUtil.applicationContext.getBean("privilege_InfoService");
//        int privilege_id = privilege_infoService.getPrivilege_IdByRequest(request_name);
//        System.out.println("......start...." + privilege_id);
//        String[] privilege_list = student.getPrivilege_list().split("#");
//        int i = 0;
//        while (i < privilege_list.length){
//            if (Integer.parseInt(privilege_list[i]) == privilege_id)
//                break;
//            i++;
//        }
//        if (i == privilege_list.length){
//            flag = false;
//            try {
//                response.sendRedirect("no_privilege");
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
        return  flag;
    }
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView){
        //String requestURL = request.getRequestURI();
        //System.out.println(requestURL);
    }
}
